package com.ceiec.cad.questionrepository;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;

/**
 * 问题来源：
 * 今年行情这么差，到底如何进大厂？
 * https://www.cnblogs.com/cxuanBlog/p/12719416.html
 */
@Slf4j
@Data
@Component
public class QuestionRepository implements IQuestionRepositoryService {
    private List<String> questions = new ArrayList<>();

    Random random = new Random();

    public Boolean initOrNot = false;

    public void init() {
        ClassPathResource resource = new ClassPathResource("question-list1");
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8);
            BufferedReader reader = new BufferedReader(inputStreamReader);

            String length = "";
            while ((length = reader.readLine()) != null) {
                if (!StringUtils.isEmpty(length)) {
                    if (Objects.equals(length.trim(), "")) {
                        continue;
                    }
                    questions.add(length);
                }
            }

            initOrNot = true;
        } catch (IOException e) {
            log.error("e:{}", e);
        }

    }


    @Override
    public String getOneQuestion() {
        if (!initOrNot) {
            init();
            if (!initOrNot) {
                throw new RuntimeException();
            }
        }

        int i = random.nextInt(questions.size() - 1);
        return questions.get(i);
    }
}
